﻿using System;
using System.Data;
using System.IO;

namespace Listener_SMS
{
    /// <summary>
    /// 猫机短信观察者
    /// </summary>
    public class SmsObserver
    {
        static SmsObserver smsObserver;

        /// <summary>
        /// 当前主键
        /// </summary>
        int currentId = 0;

        /// <summary>
        /// 执行次数
        /// </summary>
        int executeCount = 0;

        /// <summary>
        /// 路径
        /// </summary>
        string FilePath = "";

        public delegate void ListenerHandler(DataTable dtNowSms);

        ListenerHandler listenerHandler;

        /// <summary>
        /// 初始化短信观察者
        /// </summary>
        /// <param name="_FilePath">文件路径</param>
        /// <returns></returns>
        public static SmsObserver init(string _FilePath)
        {
            if (string.IsNullOrEmpty(_FilePath))
            {
                throw new Exception("SmsObserver 观察者路径不能为空： _FilePath");
            }
            if (!File.Exists(_FilePath))
            {
                throw new Exception("SmsObserver 被观察对象不存在：" + _FilePath);
            }
            if (smsObserver == null)
            {
                smsObserver = new SmsObserver();
            }
            else
            {
                FileObserverUtil.WatchStartOrSopt(false);
            }
            smsObserver.FilePath = _FilePath;
            return smsObserver;
        }

        public SmsObserver setListener(ListenerHandler listenerHandler) {
            this.listenerHandler = listenerHandler;
            return smsObserver;
        }

        /// <summary>
        /// 注册观察者
        /// </summary>
        /// <returns></returns>
        public bool Register()
        {
            bool isSuccess = false;
            try
            {
                string DirectoryName = Path.GetDirectoryName(FilePath);
                string FileName = Path.GetFileName(FilePath);
                FileObserverUtil.WatcherStrat(DirectoryName, FileName, false, 
                    (result) => 
                    {
                        if (result.type == WatcherType.Changed)
                        {
                            executeCount++;
                            DataTable dtNowSms = this.GetNowSms();
                            bool isEmpty = dtNowSms == null || (dtNowSms != null && dtNowSms.Rows.Count == 0);
                            if (!isEmpty)
                            {
                                this.listenerHandler(dtNowSms);
                            }
                        }
                    });
                //设置当前最后一条短信id
                this.SetCurrentId();
                isSuccess = true;
                Console.WriteLine("SmsObserver 短信观察者已就位");
            }
            catch(Exception e)
            {
                Console.WriteLine(e.Message);
            }
            return isSuccess;
        }

        /// <summary>
        /// 设置当前最后一条短信id
        /// </summary>
        public void SetCurrentId()
        {
            string sql = "SELECT TOP 1 MSG_Inbox.* FROM MSG_Inbox ORDER BY id DESC;";
            DataTable dt = DbHelperACE.Query(sql).Tables[0];
            if (dt != null && dt.Rows.Count > 0)
            {
                DataRow row = dt.Rows[0];
                this.currentId = Convert.ToInt32(row["id"]);
            }
        }

        /// <summary>
        /// 获取新的短信内容
        /// </summary>
        /// <returns></returns>
        private DataTable GetNowSms()
        {
            DataTable dtNowSms = null;
            string sql = string.Format("SELECT MSG_Inbox.* FROM MSG_Inbox WHERE id > {0} ORDER BY id;", this.currentId);
            dtNowSms = DbHelperACE.Query(sql).Tables[0];
            if (dtNowSms != null && dtNowSms.Rows.Count > 0)
            {
                DataRow row = dtNowSms.Rows[dtNowSms.Rows.Count - 1];
                this.currentId = Convert.ToInt32(row["id"]);
            }
            return dtNowSms;
        }

        public void TestInsert() {
            string sql = "INSERT INTO MSG_Inbox (CommPort,Sender,MsgType,MsgTitle,MsgArrivedTime,imsi,imei,shoujihao,ccid)" +
                        " VALUES (11, '10010123', 1, '[yyzhanjunchuan]，短信口令420306，用于您本次登录广东4A网络安全管控平台。请在5分钟内使用。'" +
                        ",now() ,'imsi','imei','18476513737','ccid');";
            //string sql = string.Format("INSERT INTO MSG_Inbox (Sender,MsgTitle,MsgArrivedTime)  VALUES  ('10086','aaaaaaa[213],123456','2019-10-16-16:26:00'); ");
            DbHelperACE.ExecuteSql(sql);
        }

        public void TestInsert(string mobile,string msgContent)
        {
            string sql = "INSERT INTO MSG_Inbox (CommPort,Sender,MsgType,MsgTitle,MsgArrivedTime,imsi,imei,shoujihao,ccid)" +
                        " VALUES (11, '10010123', 1, '"+ msgContent + "'" +
                        ",now() ,'imsi','imei','"+ mobile + "','ccid');";
            //string sql = string.Format("INSERT INTO MSG_Inbox (Sender,MsgTitle,MsgArrivedTime)  VALUES  ('10086','aaaaaaa[213],123456','2019-10-16-16:26:00'); ");
            DbHelperACE.ExecuteSql(sql);
        }
    }
}
